const commentService = require('../service/comment.service')
const {
	COMMENT_PUBLISH_FAILED,
	COMMENT_REPLY_FAILED
} = require('../config/error')
const { buildNestedComments } = require('../utils/handle-comment')
class CommentController {
	async create(ctx, next) {
		try {
			// 1.获取body中的参数
			const { content, post_id } = ctx.request.body
			const { id } = ctx.user
			// 2.操作数据库, 将数据进行存储
			const result = await commentService.create(content, post_id, id)
			ctx.body = {
				code: 0,
				message: '发表评论成功～'
			}
		} catch (error) {
			console.log(error)
			ctx.app.emit('error', COMMENT_PUBLISH_FAILED, ctx)
		}
	}
	async reply(ctx, next) {
		try {
			// 1.获取body中的参数
			const { content, post_id, parent_id } = ctx.request.body
			const { id } = ctx.user
			// 2.操作数据库, 将数据进行存储
			const result = await commentService.reply(content, post_id, parent_id, id)
			ctx.body = {
				code: 0,
				message: '回复评论成功～'
			}
		} catch (error) {
			console.log(error)
			ctx.app.emit('error', COMMENT_REPLY_FAILED, ctx)
		}
	}

	async searchComment(ctx, next) {
		try {
			const { post_id } = ctx.params
			const result = await commentService.searchComment(post_id)
			const comments = buildNestedComments(result)
			ctx.body = {
				code: 0,
				message: '查询评论成功~',
				data: comments
			}
		} catch (error) {}
	}

	async removeComment(ctx, next) {
		try {
			const { comment_id } = ctx.params
			const result = await commentService.removeComment(comment_id)
			ctx.body = {
				code: 0,
				message: '删除评论成功'
			}
		} catch (error) {
			console.log(error)
		}
	}
}

module.exports = new CommentController()
